// PasswordDatabase.java
package com.example.passwordguard;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class PasswordDatabase extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "PasswordVault.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "passwords";

    private static final String COLUMN_ID = "id";
    private static final String COLUMN_APP = "application";
    private static final String COLUMN_USER = "username";
    private static final String COLUMN_PASS = "password";

    public PasswordDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_NAME + " (" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_APP + " TEXT, " +
                COLUMN_USER + " TEXT, " +
                COLUMN_PASS + " TEXT)";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean addPassword(String app, String user, String pass) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_APP, app);
        cv.put(COLUMN_USER, user);
        cv.put(COLUMN_PASS, pass);
        long result = db.insert(TABLE_NAME, null, cv);
        return result != -1;
    }

    public List<String> getAllPasswords() {
        List<String> passwordList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);

        if (cursor.moveToFirst()) {
            do {
                String entry = "应用: " + cursor.getString(1) +
                        "\n用户: " + cursor.getString(2) +
                        "\n密码: " + cursor.getString(3) + "\n";
                passwordList.add(entry);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return passwordList;
    }
}